package org.jgs1904.elasticsearchapi.doc;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.jgs1904.elasticsearchapi.doc.entity.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 墨苍璃
 * @date 2023年06月05日23时50分
 * <p>
 * 批量添加document
 */
public class BatchInsertDoc {

    public static void main(String[] args) throws IOException {

        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建一个批量数据集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().create(d -> d.document(new User("test1", "male", 19)).id("1003").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(d -> d.document(new User("test2", "female", 20)).id("1004").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(d -> d.document(new User("test3", "female", 21)).id("1005").index("user_test")).build());

        // 调用bulk方法执行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));

        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }

}
